package com.awenhui.demo.core.exception;

import java.io.PrintWriter;
import java.io.StringWriter;

import com.awenhui.demo.core.base.ActionResult;
import com.awenhui.demo.core.base.IBaseEnum;
import com.awenhui.demo.core.base.ResultCode;

/**
 * 全局通用操作行为异常类
 * 
 * @author yuxf
 */
public class ActionException extends RuntimeException {

    private static final long serialVersionUID = 3001137375719770241L;
    /**
     * 错误异常结果
     */
    private ActionResult<?> result;

    public ActionException() {

    }

    /**
     * 构造函数
     *
     * @param code 响应代码
     */
    public ActionException(IBaseEnum code) {
        this.setResult(new ActionResult<>(code));
    }

    /**
     * 构造函数
     *
     * @param code 响应代码
     * @param data 业务数据
     */
    public ActionException(IBaseEnum code, Object data) {
        this.setResult(new ActionResult<>(code, data));
    }

    /**
     * 构造函数
     *
     * @param message 消息提示
     */
    public ActionException(String message) {
        super(message);
        this.result = new ActionResult<String>(ResultCode.UNKNOWN_ERROR, message);
    }

    /**
     * 构造函数
     *
     * @param code    响应代码
     * @param message 消息提示
     */
    public ActionException(int code, String message) {
        super(message);
        this.result = new ActionResult<>(code, message);
    }

    /**
     * 构造函数
     *
     * @param result HTTP响应接口输出结果实体
     */
    public ActionException(ActionResult<Object> result) {
        super(result.getMessage());
        this.result = result;
    }

    public void setResult(ActionResult<Object> result) {
        this.result = result;
    }

    /**
     * 获取错误堆栈信息
     *
     * @param throwable
     * @return
     */
    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            throwable.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }

    public Object getResult() {
        return result;
    }

    /**
     * 获取错误堆栈信息
     *
     * @return
     */
    public String getStackTraceString() {
        return getStackTrace(this);
    }

}